package com.ingenio.siot.servlet;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.ingenio.siot.Helper;
import com.ingenio.siot.adapter.TrazabilidadAdapter;
import com.ingenio.siot.entity.Punto;

/**
 * Servlet implementation class TrazabilidadMovilServlet
 */
@WebServlet("/TrazabilidadMovil")
public class TrazabilidadMovilServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TrazabilidadMovilServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		TrazabilidadAdapter ta = new TrazabilidadAdapter();
		Timestamp inicio = new Timestamp(Long.parseLong(request.getParameter("desde")));
		Timestamp fin = new Timestamp(Long.parseLong(request.getParameter("hasta")));
		Integer mid =  Integer.parseInt(request.getParameter("mid"));
		List<Punto> puntos = ta.devolverTrazabilidad(mid, inicio, fin);
		try{		
			JSONObject json = new JSONObject();
			JSONArray ja = new JSONArray();
			
			for (Punto p : puntos) {
			   JSONObject jo = new JSONObject();
			   jo.put("lat", p.getLatitud());
			   jo.put("lng", p.getLongitud());
			   jo.put("fecha", p.getFecha());
			   ja.put(jo);
			}
			json.put("puntos", ja);
			response.setContentType("application/json");
			response.getWriter().write(json.toString());
		}
		catch(Exception e){
			
		}
	}
}
